package com.campus.happy;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;

import com.campus.utils.Http;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.widget.ImageView;

public class NetImg extends ImageView {
	String url;

	public NetImg(Context context, String url) {
		super(context);
		this.url = url;
		// TODO Auto-generated constructor stub
	}

	void go() {
		try {

			final File file = new File(
					Environment.getExternalStorageDirectory() + "/pack/"
							+ url.hashCode());
			if (file.exists()) {

				Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
				if (getTag().equals(url))
					setImageBitmap(bm);
			} else {
				new Thread() {
					public void run() {
						try {
							final byte[] b = CookieHttp.get(url);
							new FileOutputStream(file).write(b);
							Handler handler = new Handler(
									Looper.getMainLooper());
							handler.post(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									Bitmap bm = BitmapFactory.decodeByteArray(
											b, 0, b.length);
									if (getTag().equals(url))
										setImageBitmap(bm);
								}
							});
						} catch (MalformedURLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				}.start();

			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
